<?php
/**
*   Write (append) log messages to text file
*
*
**/
class Yz_Log_Writer_Text
    extends Yz_Class
    implements Yz_Log_Writer_Interface
{

    /**
     *  @var string file : file name
     */
    protected $file;

    /**
     *  @var string(int)
     */
    protected $logId;


    /**
     *
     */
    public function __toString()
    {
        $class = get_class($this);
        return "Object<{$class}({$this->file})>";
    }

    /**
     *   initialization
     *   @param string fileName : path to log file
     */
    public function __construct( $fileName )
    {
        if (is_file($fileName) && is_writable($fileName)) {
            $this->file = realpath($fileName);
        }
    }

    /** assign the log ID
     *  @param string|int $logId
     *  @return this
     */
    public function setLogId( $logId )
    {
        $this->logId = $logId;
        return $this;
    }


    /**
     *
     */
    public function write( $msg )
    {

        // if log not initialized or no logging required, do nothing
        if ( null === $this->file ) {
            return 0;
        }

        file_put_contents( $this->file,
            $this->formatMessage($msg),
            FILE_APPEND
        );

        return 0;
    }


    /**
     *
     */
    protected function formatMessage($msg)
    {
        return sprintf( "[%s]+%.3fs %s\n",
            $this->logId,
            Yz_Date::getElapsedTime(),
            $msg
        );
    }

} // class

